package com.rain.shoppingscienceproj.ui.activity.setting;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.alibaba.sdk.android.oss.ClientConfiguration;
import com.alibaba.sdk.android.oss.common.auth.OSSAuthCredentialsProvider;
import com.rain.shoppingscienceproj.Config;
import com.rain.shoppingscienceproj.R;
import com.rain.shoppingscienceproj.http.BaseSubscriber;
import com.rain.shoppingscienceproj.http.ExceptionHandle;
import com.rain.shoppingscienceproj.http.RetrofitClient;
import com.rain.shoppingscienceproj.ui.activity.BaseActivity;
import com.rain.shoppingscienceproj.ui.activity.login.LoginActivity;
import com.rain.shoppingscienceproj.ui.base.GlobalData;
import com.rain.shoppingscienceproj.ui.utile.DeviceUtils;
import com.rain.shoppingscienceproj.ui.utile.TitleUtils;
import com.rain.shoppingscienceproj.utils.ActionSheetDialog;
import com.rain.shoppingscienceproj.utils.AppManager;
import com.rain.shoppingscienceproj.utils.ImageLoader;
import com.rain.shoppingscienceproj.utils.ImageUtils;
import com.rain.shoppingscienceproj.utils.LoadingDialog;
import com.rain.shoppingscienceproj.utils.OssUtils;
import com.rain.shoppingscienceproj.utils.toast.ToastUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.ResponseBody;
import picker.prim.com.primpicker_core.PrimPicker;
import picker.prim.com.primpicker_core.entity.MimeType;
import pub.devrel.easypermissions.EasyPermissions;

/**
 * 个人资料
 */
public class UserInfoActivity extends BaseActivity {

    @BindView(R.id.head_photo)
    ImageView head_photo;
    @BindView(R.id.tv_member)
    TextView tv_member;
    @BindView(R.id.et_nickname)
    EditText et_nickname;

    @BindView(R.id.tv_sex)
    TextView tv_sex;
    @BindView(R.id.bar)
    ProgressBar bar;
    @BindView(R.id.textView)
    TextView textView;

    private int sexs = 0;
    String mobile = "";
    boolean isMobile = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_info);
        AppManager.getAppManager().addActivity(this);
        ButterKnife.bind(this);
        TitleUtils.TitleRightText(this, "个人资料", "保存");
        TitleUtils.mRightText.setTextColor(getResources().getColor(R.color.white));
        loadingDialog = new LoadingDialog(this, "正在加载...");
        userInfo = GlobalData.getUserInfo();
        initData();

    }

    @Override
    protected void onRestart() {
        super.onRestart();
        mobile = GlobalData.getMobile();
        if (!"".equals(mobile) && null != mobile) {
            tv_member.setText(mobile);
        }
    }

//    @OnClick(R.id.rl_mobile)
//    void mobile() {
//        startActivitys(BindTelActivity.class);
//    }

    @OnClick(R.id.rl_right)
    void save() {
        if (!"".equals(mobile) && null != mobile) {
            isMobile = true;
        }
        String nick_name = et_nickname.getText().toString().trim();
//        String mobile = tv_member.getText().toString().trim();
        String headImage = textView.getText().toString().trim();
        Map<String, String> map = new HashMap<>();
        map.put("token", userInfo.getToken());
        map.put("sex", sexs + "");
        map.put("userName", nick_name);
        if (!headImage.isEmpty()) {
            map.put("userImage", headImage);
        }
        loadingDialog.show();
        RetrofitClient.getInstance(this)
                .createBaseApi()
                .upUserData(map, new BaseSubscriber<ResponseBody>(this) {
                    @Override
                    public void onError(ExceptionHandle.ResponeThrowable e) {
                        ToastUtils.showShortToast("网络错误");
                        loadingDialog.dismiss();
                    }

                    @Override
                    public void onNext(ResponseBody responseBody) {
                        super.onNext(responseBody);
                        loadingDialog.dismiss();
                        try {
                            String request = responseBody.string();
                            JSONObject json = new JSONObject(request);
                            int status = json.getInt("code");
                            if (status == 0) {
                                ToastUtils.showShortToast("修改成功");
                                userInfo.setSex(sexs);
                                userInfo.setNickname(nick_name);
                                userInfo.setAvatarurl(headImage);
                                GlobalData.setUserInfo(userInfo);
                            } else {
                                String jsonString = json.getString("message");
                                if (jsonString.contains("token")) {
                                    startActivitys(LoginActivity.class, 1);
                                    ToastUtils.showShortToast(jsonString);
                                } else {
                                    ToastUtils.showShortToast(jsonString);
                                }
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
    }

    @OnClick(R.id.rl_image)
    void image() {
        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {

            //权限还没有授予，需要在这里写申请权限的代码
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    1001);
            return;
        }
        if (EasyPermissions.hasPermissions(this, permissions)) {
            //已经打开权限
            if (ContextCompat.checkSelfPermission(this,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE)
                    != PackageManager.PERMISSION_GRANTED) {

                //权限还没有授予，需要在这里写申请权限的代码
                ActivityCompat.requestPermissions(this,
                        new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                        1001);
                return;
            } else {
                PrimPicker
                        .with(this)
                        .choose(MimeType.ofImage())
                        .setSpanCount(Integer.parseInt(3 + ""))
                        .setMaxSelected(Integer.parseInt(1 + ""))
                        .setImageLoader(new ImageLoader())
                        .setShowSingleMediaType(true)
                        .setCapture(true)
                        .lastGo(1001);
            }
        } else {
            //没有打开相关权限、申请权限
            ToastUtils.showShortToast("权限不足");
//            EasyPermissions.requestPermissions(this, "需要获取您的相册、照相使用权限", 1, permissions);

        }
    }

    @OnClick(R.id.rl_sex)
    void sex() {
        new ActionSheetDialog(this).builder().setCancelable(true).setCanceledOnTouchOutside(false)
                .setTitle("选择性别")
                .addSheetItem("男", ActionSheetDialog.SheetItemColor.Blue, which -> upSex(1))
                .addSheetItem("女", ActionSheetDialog.SheetItemColor.Blue, which -> upSex(0))
                .show();
    }

    private void upSex(int sex) {
        sexs = sex;
        userInfo.setSex(sex);
        if (sex == 0) {
            tv_sex.setText("女");
        } else {
            tv_sex.setText("男");
        }
    }


    private void initData() {
        OssUtils.oss(UserInfoActivity.this, head_photo, bar, textView,1);
        if (userInfo.getUsername().equals("")) {
            ToastUtils.showShortToast("请重新登陆。");
        } else {
            tv_member.setText(userInfo.getUsername());
        }
        if (null != userInfo.getAvatarurl() || !"".equals(userInfo.getAvatarurl())) {
            ImageUtils.imageCircle(this, userInfo.getAvatarurl(), head_photo);
            textView.setText(userInfo.getAvatarurl());
        }
        et_nickname.setText(userInfo.getNickname());
        if (userInfo.getSex() == 1) {
            tv_sex.setText("男");
        } else {
            tv_sex.setText("女");
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1001 && resultCode == Activity.RESULT_OK) {
            List<String> pathlist = PrimPicker.obtainPathResult(data);
            if (pathlist != null && pathlist.size() != 0) {
                File file = new File(pathlist.get(0));
                String deviceId = DeviceUtils.getUniqueId(this);
                bar.setVisibility(View.VISIBLE);
                OssUtils.setmService(deviceId + file.getName(), pathlist.get(0));
            }
        } else if (requestCode == Config.REQUESTCODE_AUTH && resultCode == RESULT_OK) {
            if (data != null) {
                String url = data.getStringExtra("url");
                OSSAuthCredentialsProvider provider = new OSSAuthCredentialsProvider(url);
                ClientConfiguration conf = new ClientConfiguration();
                conf.setConnectionTimeout(15 * 1000); // 连接超时，默认15秒
                conf.setSocketTimeout(15 * 1000); // socket超时，默认15秒
                conf.setMaxConcurrentRequest(5); // 最大并发请求书，默认5个
                conf.setMaxErrorRetry(2); // 失败后最大重试次数，默认2次

            }
        }
    }
}
